
using System;
using System.Collections;
using Qdb.CS.Internal.Objectexchange;
using Qdb.Foundation;
using Qdb.Internal;
using Qdb.Internal.Marshall;

namespace Qdb.CS.Internal.Objectexchange
{
	public class StandardReferenceCollector : IReferenceCollector
	{
		private Transaction _transaction;

		public StandardReferenceCollector(Transaction transaction)
		{
			_transaction = transaction;
		}

		public virtual IEnumerator ReferencesFrom(int id)
		{
			CollectIdContext context = CollectIdContext.ForID(_transaction, id);
			ClassMetadata classMetadata = context.ClassMetadata();
			if (null == classMetadata)
			{
				// most probably ClassMetadata reading
				return Iterators.EmptyIterator;
			}
			if (classMetadata.IsPrimitive())
			{
				throw new InvalidOperationException(classMetadata.ToString());
			}
			if (!Handlers4.IsCascading(classMetadata.TypeHandler()))
			{
				return Iterators.EmptyIterator;
			}
			classMetadata.CollectIDs(context);
			return new TreeKeyIterator(context.Ids());
		}
	}
}
